import { useColorMode, usePreferredDark } from '@vueuse/core';
import { useAppStore } from '@/stores';
//  动效主题切换
export default function useTheme() {
  const preferredDark = usePreferredDark();
  const appStore = useAppStore();

  const colorMode = useColorMode({
    selector: 'body',
    attribute: 'arco-theme',
    storageKey: 'arco-theme',
    initialValue: 'dark',
    modes: {
      light: 'light',
      dark: 'dark',
      auto: 'system',
    },
  });

  const toggleThemeAnimate = (
    x: number = 0,
    y: number = 0,
    isDarks: boolean,
  ) => {
    const endRadius = Math.hypot(
      Math.max(x, window.innerWidth - x),
      Math.max(y, window.innerHeight - y),
    );

    const transition = document.startViewTransition(() => {
      const root = document.documentElement;
      root.classList.remove(isDarks ? 'dark' : 'light');
      root.classList.add(isDarks ? 'light' : 'dark');

      // 主题切换
      colorMode.value = isDarks ? 'dark' : 'light';
      appStore.setTheme(colorMode.value);
    });

    // 效果实现
    transition.ready.then(() => {
      const clipPath = [
        `circle(0px at ${x}px ${y}px)`,
        `circle(${endRadius}px at ${x}px ${y}px)`,
      ];
      document.documentElement.animate(
        {
          clipPath: isDarks ? [...clipPath].reverse() : clipPath,
        },
        {
          duration: 800,
          easing: 'ease-in',
          pseudoElement: isDarks
            ? '::view-transition-old(root)'
            : '::view-transition-new(root)',
        },
      );
    });
  };

  const toggleTheme = (
    event: MouseEvent,
    mode: 'light' | 'dark' | 'system',
  ) => {
    if (mode === 'system') {
      toggleThemeAnimate(event.clientX, event.clientY, preferredDark.value);
    } else {
      toggleThemeAnimate(event.clientX, event.clientY, mode === 'dark');
    }
  };

  return {
    colorMode,
    toggleTheme,
  };
}
